package com.boxin.ims.modules.wechat.web.front;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.boxin.ims.modules.wechat.entity.JiuWechatMember;
import com.boxin.ims.modules.wechat.entity.LangType;
import com.boxin.ims.modules.wechat.entity.WeChat;
import com.boxin.ims.modules.wechat.service.JiuWechatMemberService;
import com.boxin.ims.modules.wechat.utils.WechatCacheUtils;
import com.boxin.ims.modules.wechat.utils.WechatInterfaceUtils;
import com.boxin.weixin.entity.Oauth2Token;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.utils.CookieUtils;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.sys.entity.User;
import com.thinkgem.jeesite.modules.sys.service.SystemService;


/**
 * 网页授权(花客授权)
 * @author Administrator
 *
 */
@Controller
@RequestMapping(value = Global.FRONT_PATH+"/oauth")
public class OAuthController extends BaseController {
	
	@Autowired
	private JiuWechatMemberService jiuWechatMemberService;
	
	@Autowired
	private SystemService systemService;

	/**
	 * 网页授权(弹出授权页面，可通过openid拿到昵称、性别、所在地。并且，即使在未关注的情况下，只要用户授权，也能获取其信息)
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "redirectUserinfo")
	public String redirectUserinfo(HttpServletRequest request, HttpServletResponse response,Model model){
		String state = request.getParameter("state");
		String userId =state ;
		String redirect =CookieUtils.getCookie(request, "redirectUrl") ;
		
		if(StringUtils.isBlank(userId)){
			return error(request);
		}
		WeChat weChat =  WechatCacheUtils.getWeChatByUserId(Long.parseLong(userId));
		
		String code = request.getParameter("code");
		String appid =weChat.getAppId();
		String secret = weChat.getAppSecret();
		Oauth2Token oauth2Token =null;
		try {
			oauth2Token= WechatInterfaceUtils.getOAuth2Token(appid, secret, code);
		} catch (Exception e) {
			return error(request);
		}
		String openId = oauth2Token.getOpenid();
		if(StringUtils.isBlank(openId)){
			return error(request);
		}
		CookieUtils.setCookie(response, "userinfo_openid",openId);
		
		JiuWechatMember member  =  jiuWechatMemberService.getByUserIdAndOpenId(Long.parseLong(userId), openId);
		if(member==null){
			System.err.println("========》拉授权 保存会员信息  准备执行");
			member = addWechatMember(oauth2Token.getToken(), Long.parseLong(userId), openId, request);
		}
		
		if(redirect.indexOf("?")>=1){
			return "redirect:"+redirect+"&uid="+userId;
		}else{
			return "redirect:"+redirect+"?uid="+userId;
		}
	}
	
	
	
	
	
	/**
	 * 网页授权(不弹出授权页面，直接跳转，只能获取用户openid)
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "redirectAPI")
	public String redirectAPI(HttpServletRequest request, HttpServletResponse response,Model model){
		String state = request.getParameter("state");
		String userId =state ;
		String redirect =CookieUtils.getCookie(request, "redirectUrl") ;
		
		if(StringUtils.isBlank(userId)){
			return error(request);
		}
		WeChat weChat =  WechatCacheUtils.getWeChatByUserId(Long.parseLong(userId));
		
		
		String code = request.getParameter("code");
		String appid =weChat.getAppId();
		String secret = weChat.getAppSecret();
		Oauth2Token oauth2Token =null;
		try {
			oauth2Token= WechatInterfaceUtils.getOAuth2Token(appid, secret, code);
		} catch (Exception e) {
			return error(request);
		}
		String openId = oauth2Token.getOpenid();
		//CookieUtils.setCookie(response, "tp_open_id",openId);
		request.getSession().setAttribute("tp_open_id", openId);
		if(StringUtils.isBlank(openId)){
			return error(request);
		}
		if(redirect.indexOf("?")>=1){
			return "redirect:"+redirect;
		}else{
			return "redirect:"+redirect;
		}
	}
	
	
	
	
	private String error(HttpServletRequest request){
		request.setAttribute("url", "javascript:WeixinJSBridge.call('closeWindow');");
		request.setAttribute("msg", "网络信号不稳定，请重新进入!");
		request.setAttribute("btnMsg", "关闭");
		return "modules/shopping/front/error";
	}
	
	/**
	 * 新增会员对象(网页授权)
	 * @param user
	 * @param wechatId
	 * @param weChat
	 * @param request
	 * @return
	 */
	public JiuWechatMember addWechatMember(String token,Long userId,String openId,HttpServletRequest request){
		System.err.println("========》拉授权 保存会员信息  执行=====");
		JiuWechatMember wechatMember = jiuWechatMemberService.getByUserIdAndOpenId(userId, openId);
		if(wechatMember == null){	//不存在则添加
	
			wechatMember = new JiuWechatMember();
			User user = systemService.getUser(userId);//获得用户信息
			wechatMember.setUser(user);
			wechatMember.setOpenId(openId);
			wechatMember.setSex("保密");
			try {
				JiuWechatMember temp =WechatInterfaceUtils.getUserMessageBysns(token, openId, LangType.zh_CN);
				if(temp!=null){
					
					if(StringUtils.isNotEmpty(temp.getNickname())){
						wechatMember.setName(temp.getNickname());
						wechatMember.setNickname(temp.getNickname());
					}else{
						wechatMember.setNickname("匿名");
						wechatMember.setName("匿名");
					}
					
					wechatMember.setAge(temp.getAge());
					wechatMember.setHeadimgurl(temp.getHeadimgurl());
					wechatMember.setCity(temp.getCity());
					wechatMember.setCountry(temp.getCountry());
					String sex = temp.getSex();
					if("1".equals(sex)){
						wechatMember.setSex("男");
					}else if("2".equals(sex)){
						wechatMember.setSex("女");
					}else{
						wechatMember.setSex("保密");
					}
					wechatMember.setProvince(temp.getProvince());
					wechatMember.setLanguage(temp.getLanguage());
				}
			} catch (Exception e) {
				
			}

			jiuWechatMemberService.save(wechatMember);

			if(wechatMember.getId()==null || wechatMember.getId() <= 0)	{
				jiuWechatMemberService.save(wechatMember);
			}
			//生成会员卡号
			wechatMember.setNumber(StringUtils.leftPad("" + wechatMember.getId(), 10, "0")); // 会员卡号
			
			if(wechatMember.getName()==null || wechatMember.getName().equals("匿名")){
				wechatMember.setName("会员"+wechatMember.getId());
				wechatMember.setNickname("会员"+wechatMember.getId());
			}

			jiuWechatMemberService.save(wechatMember);
			// 把会员表推荐码字段置成会员ID 推荐码=会员ID
		}else{
			
		}

		return wechatMember;
	}
	

}
